package com.wbs.consumer;

import com.wbs.controller.SendSmsController;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RocketMQMessageListener(topic = "captcha",consumerGroup = "captcha-queue")
public class UserConsumer implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {
    @Autowired
    private SendSmsController sendSmsController;

    @Override
    public void onMessage(String s) {
        System.out.println(s);
    }
    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                //所有消息都存在List<MessageExt> list中
                MessageExt messageExt = list.get(0);
                //消息体内容
                String number = new String(messageExt.getBody());
//                System.out.println(s);
                try {
                    sendSmsController.message(number);
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }catch (Exception e){
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
        });
    }
}
